import threading

from blocking_resource import BlockingResource
from response import CommandListResponse

class OnlineUser():
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.cmdQueue = []
        self.state = 0 # user_state.INIT
        self.cond = threading.Condition()

    def addCmd(self, cmd, args=[]):
        self.cond.acquire()
        self.cmdQueue.append({'cmd': cmd, 'args': args})
        self.cond.notify()
        self.cond.release()

    def addCard(self, card):
        self.cards.append(card)
        self.cards.sort()

    def setState(self, state):
        self.state = state

    def getCmd(self):
        self.cond.acquire()
        if self.cmdQueue:
            self.cond.release()
            return self.cmdQueue.pop(0)
        else:
            self.cond.wait()
            self.cond.notify()
            self.cond.release()
            return self.cmdQueue.pop(0)


class OnlineUserList(BlockingResource):
    onlineUser = {}
    readyUser = 0

    def getAll(self):
        return list(self.onlineUser.itervalues())

    def genId(self):
        return str(len(self.onlineUser))

    def add(self, uid, onlineUser):
        self.onlineUser[uid] = onlineUser

    def get(self, key):
        return self.onlineUser[key]

    def addCard(self, uid, card):
        self.onlineUser[uid].addCard(card)

    def addCmd(self, uid, cmd, args):
        self.onlineUser[uid].addCmd(cmd, args)

    def broadcastCmd(self, cmd, args, exceptUId=None):
        for user in self.onlineUser.itervalues():
            if user.id != exceptUId:
                user.addCmd(cmd, args)

    def setUserState(self, uid, state):
        self.onlineUser[uid].setState(state)
        self.readyUser += 1
        return self.readyUser

    def _render_GET(self, request):
        u_id = request.args['u_id'][0]
        cmd = self.onlineUser[u_id].getCmd()

        cmdList = []
        cmdList.insert(0, cmd)
        if len(cmd['args']) != 1:
            print '>>To %s: [%s] %s' % (u_id, cmd['cmd'], cmd['args'])
        else:
            print '>>To %s: [%s] %s' % (u_id, cmd['cmd'], cmd['args'][0])

        return CommandListResponse(cmdList)

